#!/bin/sh

# 环境变量设置
source ~/.vis_profile

# start services.
start()
{
    # 目录准备
    mkdir -p ${VIS_LOG_PATH}/nginx
    
    # 配置文件准备
    cp -f ${VIS_ROOT_PATH}/nginx/conf/nginx.conf.template ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    sed -i "s#{VIS_ROOT_PATH}#${VIS_ROOT_PATH}#g" ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    sed -i "s#{VIS_LOG_PATH}#${VIS_LOG_PATH}#g" ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    sed -i "s#{NGINX_HTTP_PORT}#${NGINX_HTTP_PORT}#g" ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    sed -i "s#{RESTFUL_HTTP_PORT}#${RESTFUL_HTTP_PORT}#g" ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    sed -i "s#{VIS_FILE_ROOT_PATH}#${VIS_FILE_ROOT_PATH}#g" ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    sed -i "s#{VIS_UPLOAD_PATH}#${VIS_UPLOAD_PATH}#g" ${VIS_ROOT_PATH}/nginx/conf/nginx.conf
    
    # 启动
    ${VIS_ROOT_PATH}/nginx/sbin/nginx -c ${VIS_ROOT_PATH}/nginx/conf/nginx.conf 2>/dev/null &
}

stop()
{
    # 关闭
    ${VIS_ROOT_PATH}/nginx/sbin/nginx -s stop &
}

restart()
{
    PIDS=`ps -ef | egrep "nginx" | grep -v "grep" | grep -v "init-nginx.sh" | awk '{print $2}'`
    if [ -z "$PIDS" ]
    then
        start
    else
        # 重启
        ${VIS_ROOT_PATH}/nginx/sbin/nginx -s reload &
    fi
}

RETVAL=0
# execute parameter:
#  @$1  start|stop|restart|...
#  @$2  shell file name.
execute()
{
    case "$1" in
        start)
            start
        ;;
        
        stop)
            stop
        ;;
        
        restart)
            restart
        ;;
        
        *)
            echo $"Usage: $2 {start|stop|restart|reload|status}"
            RETVAL=1
            exit $RETVAL
    esac
}

# execute shell file.
execute "$1" "$0"

RETVAL=$?

exit $RETVAL
